package menu

import (
	"context"
	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/net/ghttp"
	v1 "ruoyi-vue-pro-go/api/menu/v1"
	"ruoyi-vue-pro-go/internal/dao"
	"ruoyi-vue-pro-go/internal/model/do"
	"ruoyi-vue-pro-go/internal/service"
)

type (
	sMenu struct{}
)

func init() {
	service.RegisterMenu(New())
}

func New() service.IMenu {
	return &sMenu{}
}

func (s *sMenu) GetOne(ctx context.Context, req *v1.GetOneReq) (res *v1.GetOneRes, err error) {
	res = &v1.GetOneRes{}
	err = dao.SystemMenu.Ctx(ctx).Where(do.SystemMenu{
		Id: req.Id,
	}).Scan(&res.SystemMenu)
	return
}

func (s *sMenu) GetList(ctx context.Context, req *v1.GetListReq) (res *v1.GetListRes, err error) {
	res = &v1.GetListRes{}
	err = dao.SystemMenu.Ctx(ctx).Scan(&res.List)
	return
}

func (s *sMenu) GetListByIds(ctx context.Context, req *v1.GetListByIdsReq) (res *v1.GetListByIdsRes, err error) {
	res = &v1.GetListByIdsRes{}
	err = dao.SystemMenu.Ctx(ctx).WhereIn("id", req.MenuIds).Order("sort asc").Scan(&res.List)
	if err != nil {
		return nil, err
	}
	return res, nil
}

func (s *sMenu) Create(ctx context.Context, req *v1.CreateReq) (res *v1.CreateRes, err error) {
	res = &v1.CreateRes{}
	var cls = dao.SystemMenu.Columns()
	count, err := dao.SystemMenu.Ctx(ctx).
		Where(cls.Name, req.Name).Count()
	if err != nil {
		return res, err
	}
	if count > 0 {
		return res, gerror.NewCode(gcode.CodeDbOperationError, "菜单已存在")
	}
	_, err = dao.SystemMenu.Ctx(ctx).Data(req).Insert()
	if err != nil {
		return res, gerror.NewCode(gcode.CodeDbOperationError, "menu create failed")
	}
	return
}

func (s *sMenu) Delete(ctx context.Context, req *v1.DeleteReq) (res *v1.DeleteRes, err error) {
	res = &v1.DeleteRes{}
	var cls = dao.SystemMenu.Columns()
	_, err = dao.SystemMenu.Ctx(ctx).Where(cls.Id, req.Id).Delete()
	if err != nil {
		return nil, gerror.NewCode(gcode.CodeDbOperationError, "menu delete failed")
	}
	return
}

func (s *sMenu) Update(ctx context.Context, req *v1.UpdateReq) (res *v1.UpdateRes, err error) {
	res = &v1.UpdateRes{}
	// 这里需要获取当前用户名和租户id
	r := ghttp.RequestFromCtx(ctx)
	username := r.GetCtxVar("username").String()
	req.Creator = username
	req.Updater = username
	_, err = dao.SystemMenu.Ctx(ctx).Data(req).Where(do.SystemMenu{
		Id: req.Id,
	}).Update()
	if err != nil {
		return nil, gerror.NewCode(gcode.CodeDbOperationError, "menu update failed")
	}
	return
}
